import React, { useState, useEffect } from 'react'
import { List, Input, Button, Checkbox, message } from 'antd'
import { checkTodolist, createTodolist, deleteTodolist, getTodoList } from '@/util/request'

interface Todo {
  id: number
  title: string
  completed: boolean
}

// 待办列表
export default function TodoList() {
  // const initialTodos: Todo[] = [
  //   { id: 1, title: '完成项目文档编写', completed: false },
  //   { id: 2, title: '购买生活用品', completed: true },
  //   { id: 3, title: '学习 React 新特性', completed: false }
  // ]

  // 待办列表
  const [todos, setTodos] = useState<Todo[]>([])
  // 输入框内容
  const [newTodoTitle, setNewTodoTitle] = useState('')
  // 全局提示
  const [messageApi, contextHolder] = message.useMessage()

  useEffect(() => {
    getTodoListAsync()
  }, [])

  // 获取待办列表
  const getTodoListAsync = async () => {
    const res = await getTodoList()
    if (res.code == 200) {
      setTodos(res.data as any)
    }
  }

  // 新增待办
  const createTodo = async () => {
    if (newTodoTitle.trim() === '') {
      messageApi.open({
        type: 'error',
        content: '请输入待办'
      })
      return
    }

    const res = await createTodolist({ title: newTodoTitle })

    if (res.data.code == 200) {
      messageApi.open({
        type: 'success',
        content: '新增待办成功'
      })
      getTodoListAsync()
      setNewTodoTitle('')
    } else {
      messageApi.open({
        type: 'error',
        content: '新增待办失败'
      })
    }
  }

  // 待办是否完成
  const updateTodo = async (id: number, completed: boolean) => {
    const res: any = await checkTodolist(id, { completed })
    if (res.data.code == 200) {
      if (res.data.data.completed) {
        messageApi.open({
          type: 'success',
          content: '待办已经完成'
        })
      } else {
        messageApi.open({
          type: 'warning',
          content: '待办未完成'
        })
      }
      getTodoListAsync()
    }
  }

  // 删除待办
  const deleteTodo = async (id: number) => {
    const res: any = await deleteTodolist(id)
    if ((res.code = 200)) {
      getTodoListAsync()
      messageApi.open({
        type: 'success',
        content: '删除待办成功'
      })
    }
  }

  // 对 todos 数组进行排序，已完成的放在末尾
  const sortedTodos = todos.sort((a: any, b: any) => a.completed - b.completed)

  return (
    <>
      {contextHolder}
      <div>
        <div style={{ margin: '20px 0' }}>
          <Input placeholder="请输入待办事项" value={newTodoTitle} onChange={e => setNewTodoTitle(e.target.value)} style={{ width: '300px', marginRight: 10 }} />
          <Button onClick={createTodo} type="primary">
            增加
          </Button>
        </div>
        <div style={{ background: 'white', padding: '10px' }}>
          <List
            dataSource={sortedTodos}
            renderItem={todo => (
              <List.Item
                actions={[
                  <Button type="primary" danger onClick={() => deleteTodo(todo.id)}>
                    删除
                  </Button>
                ]}
              >
                <Checkbox checked={todo.completed} onChange={e => updateTodo(todo.id, e.target.checked)}>
                  <span style={{ textDecoration: todo.completed ? 'line-through' : 'none', color: todo.completed ? '#999' : 'inherit' }}>{todo.title}</span>
                </Checkbox>
              </List.Item>
            )}
          />
        </div>
      </div>
    </>
  )
}
